package cn.gzmli.dtt.common.service;

import cn.gzmli.dtt.common.dao.RoleDao;
import cn.gzmli.dtt.common.utils.BaseService;
import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.entity.Permission;
import cn.gzmli.dtt.common.entity.Role;
import cn.gzmli.dtt.sbzyc.exception.SystemException;
import cn.gzmli.dtt.common.utils.BaseUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Descript
 * @Author xsx
 * @Date 2017/12/25
 */
@Service
@Transactional
public class RoleService extends BaseService<Role> {

    @Autowired
    private RoleDao roleDao;

    public List<Map<String, Object>> getByCondition(HttpServletRequest request, PageInfo pageInfo) throws Exception{
        Map<String, Object> condition = this.getCondition(request);
        StringBuilder sql = new StringBuilder("SELECT * FROM role WHERE 1=1 ");
        return BaseUtil.getData(sql, condition, pageInfo, this.getDao(), "id", false);
    }

    /**
     * 查询所有角色
     * @return
     * @throws Exception
     */
    public List<Map<String, Object>> queryAllRoles() throws Exception{
      String sql="SELECT id,name FROM role ";
      return this.getDao().getJdbcTemplate().queryForList(sql);
    }

    @Override
    public Role save(Role role) throws Exception {
        Map<String, String> condition = new HashMap<>();
        condition.put("name", "="+ StrUtil.wrap(role.getName(), "'", "'"));
        condition.put("type", "="+ role.getType());
        Role r = this.getByCondition(condition);
        if (r==null){
            role.setId((Integer) this.getDao().insert(role));
        }else{
            throw new SystemException("此角色名称已存在");
        }
        return role;
    }


    @Override
    public void update(Role role) throws Exception {
        Map<String, String> condition = new HashMap<>();
        condition.put("name", "="+ StrUtil.wrap(role.getName(), "'", "'"));
        condition.put("type", "="+ role.getType());
        Role r = this.getByCondition(condition);
        if (r==null||r.getId().intValue()==role.getId().intValue()){
            role.setMenus(this.get(role.getId()).getMenus());
            this.getDao().update(role);
        }else{
            throw new SystemException("该名称已存在");
        }
    }

    public List<Map<String, Object>> getTree(HttpServletRequest request) throws Exception {
        Map<String, Object> condition = this.getCondition(request);
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT CONCAT(id, 'dttR') AS id,")
                .append("id AS realID,")
                .append("name AS name,")
                .append("type AS pId,")
                .append("'Role' AS nodeType ")
                .append("FROM role ")
                .append("WHERE 1=1 ");
        List<Map<String, Object>> data = new ArrayList<>();
        data.addAll(BaseUtil.getData(sql, condition, this.getDao()));
        this.addTreeType(request, data);
        return data;
    }

    private Map<String, Object> getCondition(HttpServletRequest request) throws Exception {
        Map<String, Object> condition = new HashMap<>();
        if (StrUtil.isNotBlank(request.getParameter("type"))){
            condition.put(" AND type=?", Integer.valueOf(request.getParameter("type")));
        }else if (StrUtil.isNotBlank(request.getParameter("types"))){
            condition.put(" AND type IN("+BaseUtil.getPlaceholder(request.getParameter("types"))+")", BaseUtil.getArgs(request.getParameter("types"), Integer.class));
        }
        if (StrUtil.isNotBlank(request.getParameter("name"))){
            condition.put(" AND name LIKE ?", "%" + request.getParameter("name") + "%");
        }
        return condition;
    }

    private void addTreeType(HttpServletRequest request, List<Map<String, Object>> data){
        Map<String, Map<String, Object>> type = new HashMap<>();
        Map<String, Object> type1 = new HashMap<>();
        type1.put("id", 1);
        type1.put("name", "系统角色");

        Map<String, Object> type2 = new HashMap<>();
        type2.put("id", 2);
        type2.put("name", "项目角色");

        type.put("1", type1);
        type.put("2", type2);

        if (StrUtil.isNotBlank(request.getParameter("types"))){
            for (String id : request.getParameter("types").split(",")){
                if (type.get(id)!=null){
                    data.add(type.get(id));
                }
            }
        }else if (StrUtil.isBlank(request.getParameter("type"))){
            data.add(type1);
            data.add(type2);
        }
    }

    @Transactional(rollbackFor=Exception.class)
    public void updateMenus(Integer id, String menuIDS) throws Exception {
        Role role = this.get(id);
        //先移除角色菜单表,再添加
        String deleteSql = "DELETE FROM role_menu WHERE roleId= "+id;
        roleDao.getJdbcTemplate().execute(deleteSql);

        StringBuilder insertSql = new StringBuilder("INSERT INTO role_menu (roleId, menuId) ");
        List<Object> args = new ArrayList<Object>();
        int i = 1;
        if (StrUtil.isNotBlank(menuIDS)){
            for (String menuID : menuIDS.split(",")){
                args.add(id);
                args.add(menuID);
                insertSql.append(" SELECT ?,? FROM DUAL UNION");
                i++;
            }
            String executeSql = insertSql.substring(0, insertSql.lastIndexOf("UNION"));
            roleDao.getJdbcTemplate().update(executeSql.toString(), args.toArray());
        }
    }
    
    public void updatePermissons(Integer id, String permissionIDS) throws Exception {
        Role role = this.get(id);
        Set<Permission> pers = null;
        if (StrUtil.isNotBlank(permissionIDS)){
        	pers = new HashSet<>();
            for (String permissionID : permissionIDS.split(",")){
                Permission per = new Permission();
                if("0".equals(permissionID)){//去除掉根节点
                    continue;
                }
                per.setId(Integer.valueOf(permissionID));
                pers.add(per);
            }
        }

        role.setPermissions(pers);
        this.getDao().update(role);
    }

    public List<Map<String, Object>>  getRolePermissionsByContion(Integer id) {
        String sql = "select * from role_permission where permission_id="+id+"";
        return this.getDao().getJdbcTemplate().queryForList(sql);

    }

}
